package com.extr.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 汉字转拼音工具类
 * @author liweipeng
 *
 */
public class Cn2SpellHelper {

	  /** 
	    * 汉字转换为汉语拼音首字母，英文、数字字符不变 
	    * @param chines 汉字 
	    * @return 拼音 
	    */  
	    public static String converterToFirstSpell(String chines){     
	    	//System.out.println("chines: "+chines);
	        try {
				String pinyinName = "";  
				char[] nameChar = chines.toCharArray();  
				HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();  
				defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
				defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);  
				for (int i = 0; i < nameChar.length; i++) {  
				    if (nameChar[i] > 128) {  
				        try {  
				        	String s[] = PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat);
				        	if(s != null && s.length > 0){
				        		pinyinName += s[0].charAt(0); 
				        	}
				        } catch (Exception e) {  
				            e.printStackTrace();  
				        }  
				    }else{  
				        pinyinName += nameChar[i];  
				    }  
				}  
				return pinyinName;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
	        return "";
	    }  
	   
	    /** 
	    * 汉字转换为汉语拼音全拼，英文、数字字符不变 
	    * @param chines 汉字 
	    * @return 拼音 
	    */  
	    public static String converterToSpell(String chines){
	    	//System.out.println("chines: "+chines);
	        try {
				String pinyinName = "";  
				char[] nameChar = chines.toCharArray();  
				HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();  
				defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
				defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);  
				for (int i = 0; i < nameChar.length; i++) {  
				    if (nameChar[i] > 128) {  
				        try {  
				            pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0];  
				        } catch (Exception e) {  
				            e.printStackTrace();  
				        }  
				    }else{  
				        pinyinName += nameChar[i];  
				    }  
				}  
				return pinyinName;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
	        return "";
	    }  
	      
	    public static void main(String[] args) {  
	    	//首拼
	        System.out.println(converterToFirstSpell("广发证券020"));  
	        //全拼
	        System.out.println(converterToSpell("广发证券020")); 
	    }  
}
